package com.baosaas.api.baseInfo.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created with IntelliJ IDEA.
 * User: Orrin
 * Date: 15-5-7
 * Time: 下午1:22
 * To change this template use File | Settings | File Templates.
 */
public class HttpPostConnect {
    protected Log log = LogFactory.getLog(getClass());


    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }

    public static String simplePostJson(String address, String head, String body)
            throws Exception {

        HttpClient client = new HttpClient();

        // client.getHostConfiguration().setHost("www.imobile.com.cn", 80,
        // "http");
        HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
        HttpMethod method = getPostJsonMethod(address, head, body);// 使用POST方式提交数据
        client.setConnectionTimeout(60000);
        client.setTimeout(1200000);
        //设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(60000);
        // 设置读数据超时时间(单位毫秒)
        managerParams.setSoTimeout(1200000);


        client.executeMethod(method);

        // 打印服务器返回的状态

        // System.out.println(method.getStatusLine());

        // 打印结果页面

        String response = method.getResponseBodyAsString();

        // 打印返回的信息

        System.out.println(response);

        method.releaseConnection();

        return response;
    }

    private static HttpMethod getPostJsonMethod(String address, String head, String body) {

        PostMethod post = new PostMethod(address);
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

        NameValuePair[] values = new NameValuePair[2];
        values[0] = new NameValuePair("head", head);
        values[1] = new NameValuePair("body", body);
        post.setRequestBody(values);
        System.out.print("head:" + head);
        System.out.print("body:" + body);
        return post;

    }
}
